package com.smcdd.cdb.dbo.cdb_dbo.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.SitePosition;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.StoreInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.UrlEvent;
import com.smcdd.cdb.dbo.cdb_dbo.service.presenter.AddMenDianPresenter;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.IAddMenDianAc;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.BitmapUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.AwaitDialog;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.QuotaAddressPopup;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.SelectPicPopupWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.net.URL;

import retrofit2.http.Url;

/**
 * 作者：Administrator on 2017/6/20 15:04
 * 邮箱：zhanghuaiha@gmail.com
 * @author zhang
 */


public class AddMenDianActivity extends BaseActivity<IAddMenDianAc,AddMenDianPresenter> implements IAddMenDianAc{
    private ImageView back,image;
    private CheckBox cb;
    private TextView add_province_and_city,add_location,add_number,add_save,add_site,add_title;
    private EditText add_name,add_person_to_contact,add_tel,add_location_info,add_remarks;
    private SelectPicPopupWindow menuWindow;
    private File tempFile;
    private String path;
    private LinearLayout add;
    /**
     * PHOTO_REQUEST_CAREMA
     * 拍照
     */
    private static final int PHOTO_REQUEST_CAREMA = 1;
    /**
     * PHOTO_REQUEST_GALLERY
     * 从相册中选择
     */
    private static final int PHOTO_REQUEST_GALLERY = 3;
    /**
     * LAT_LOG
     * 经纬度
     */
    private static final int LAT_LOG = 5;
    private static final String TAG = "AddMenDianActivity";
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private RadioGroup  add_shop_item_rg;
    private RadioButton one,two;
    private String url;
    private int type = 0;
    private String lat;
    private String log;
    private String position;
    private String position_name;
    private StoreInfo.DataBean dataBean;
    private AwaitDialog selfDialog;
    private QuotaAddressPopup quotaAddressPopup;

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        back = (ImageView) findViewById(R.id.add_back);
        image = (ImageView) findViewById(R.id.add_image);
        add_number = (TextView) findViewById(R.id.add_number);
        add_location = (TextView) findViewById(R.id.add_location);
        add_title = (TextView) findViewById(R.id.add_title);
        add_site = (TextView) findViewById(R.id.add_site);
        add_save = (TextView) findViewById(R.id.add_save);
        add_province_and_city = (TextView) findViewById(R.id.add_province_and_city);
        add_remarks = (EditText) findViewById(R.id.add_remarks);
        add_name = (EditText) findViewById(R.id.add_name);
        add_location_info = (EditText) findViewById(R.id.add_location_info);
        add_tel = (EditText) findViewById(R.id.add_tel);
        add_person_to_contact = (EditText) findViewById(R.id.add_person_to_contact);
        add = (LinearLayout) findViewById(R.id.add);
        cb = (CheckBox) findViewById(R.id.add_cb);
        add_shop_item_rg = (RadioGroup) findViewById(R.id.add_shop_item_rg);
        one = (RadioButton) findViewById(R.id.add_shop_item_one);
        two = (RadioButton) findViewById(R.id.add_shop_item_two);
        one.setOnClickListener(v -> {
            type  = 0;
        });
        two.setOnClickListener(v -> {
            type = 1;
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                quotaAddressPopup = new QuotaAddressPopup(AddMenDianActivity.this, add, (addressStr, Province, City, County, ProvinceId, CityId, CountyId) -> {
                    add_province_and_city.setText(addressStr);
                    App.EDIT.putString("addressStr", addressStr);
                    App.EDIT.putString("Province", Province);
                    App.EDIT.putString("City", City);
                    App.EDIT.putString("County", County);
                    App.EDIT.putString("ProvinceId", ProvinceId);
                    App.EDIT.putString("CityId", CityId);
                    App.EDIT.putString("CountyId", CountyId);
                    App.EDIT.commit();
                    Looper.loop();
                });
            }
        }).start();

    }

    @Override
    public void initData() {
        mPresenter.loadContacts();
        dataBean = (StoreInfo.DataBean) getIntent().getSerializableExtra("dataBean");
        if (dataBean != null) {
            add_name.setText(dataBean.getName());
            add_title.setText("更新门店");
            add_site.setText(dataBean.getPosition_name());
            add_province_and_city.setText(dataBean.getProvince_name()+"-"+ dataBean.getCity_name()+"-"+ dataBean.getArea_name());
            add_person_to_contact.setText(dataBean.getContact());
            add_tel.setText(dataBean.getTel());
            if ("0".equals(dataBean.getFrom_type())) {
                one.setSelected(true);
            }else {
                two.setSelected(true);
            }
            position = dataBean.getPosition();
            add_location.setText(dataBean.getLatitude()+","+ dataBean.getLongitude());
            add_location_info.setText(dataBean.getSpecific_address());
            url = dataBean.getImg_url();
            Glide.with(this).load(dataBean.getImg_url()).into(image);
            lat = dataBean.getLatitude();
            log = dataBean.getLongitude();
            if (dataBean.getRemark() != null) {
                add_remarks.setText((String)dataBean.getRemark());
            }

            App.EDIT.putString("Province",dataBean.getProvince_name());
            App.EDIT.putString("City",dataBean.getCity_name());
            App.EDIT.putString("County",dataBean.getArea_name());
            App.EDIT.putString("ProvinceId",dataBean.getProvince_id());
            App.EDIT.putString("CityId",dataBean.getCity_id());
            App.EDIT.putString("CountyId",dataBean.getArea_id());
            App.EDIT.commit();
        }else {
            String string = App.SP.getString("addressStr", "xxx省xxx市xxx县");
            add_province_and_city.setText(string);
        }
    }

    @Override
    public void initListener() {

        add_location.setOnClickListener(v -> {
            Intent intent  = new Intent(AddMenDianActivity.this,TencentMapActivity.class);
            startActivityForResult(intent,LAT_LOG);
        });
        add_site.setOnClickListener(v -> {mPresenter.select();});
        back.setOnClickListener(v -> finish());
        image.setOnClickListener(v -> {
            if (SdPermission()) {
                selectImgs();
            }
        } );
        //省市县三级联动
        add_province_and_city.setOnClickListener(v -> {
            quotaAddressPopup.showAddressPopup();

        });
        add_remarks.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                add_number.setText(s.length()+"/100");
            }
        });
        add_save.setSelected(true);
        cb.setOnClickListener(v -> {
            if (cb.isChecked()) {
                add_save.setSelected(true);
            }else {
                add_save.setSelected(false);
            }

        });
        add_save.setOnClickListener(v -> {
            if (cb.isChecked()) {
                Dialog("正在更新,请等待...");
                String name = add_name.getText().toString().trim();
                String contact = add_person_to_contact.getText().toString().trim();
                String tel = add_tel.getText().toString().trim();
                String location_info = add_location_info.getText().toString().trim();
                String remarks = add_remarks.getText().toString().trim();
                String location = add_location.getText().toString();
                String position_name = add_site.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtil.showToast("店铺名不能为空");
                    selfDialog.dismiss();
                    return;
                }else if ("".equals(position_name) ||TextUtils.isEmpty(position_name)){
                    ToastUtil.showToast("场所不能为空");
                    selfDialog.dismiss();
                    return;
                }else if (TextUtils.isEmpty(contact)) {
                    ToastUtil.showToast("联系人不能为空");
                    selfDialog.dismiss();
                    return;
                }else if (TextUtils.isEmpty(tel)) {
                    ToastUtil.showToast("电话不能为空");
                    selfDialog.dismiss();
                    return;
                }else if (TextUtils.isEmpty(location)) {
                    ToastUtil.showToast("位置不能为空");
                    selfDialog.dismiss();
                    return;
                }else if (TextUtils.isEmpty(location_info)) {
                    ToastUtil.showToast("详细地址不能为空");
                    selfDialog.dismiss();
                    return;
                }else if (url == null || url.length() == 0) {
                    ToastUtil.showToast("图片上传失败..");
                    selfDialog.dismiss();
                    return;
                }else {
                    if (TextUtils.isEmpty(remarks)) {
                        remarks = "";
                    }
                    String provinceId = App.SP.getString("ProvinceId", "");
                    String cityId = App.SP.getString("CityId", "");
                    String countyId = App.SP.getString("CountyId", "");
                    String province = App.SP.getString("Province", "");
                    String city = App.SP.getString("City", "");
                    String county = App.SP.getString("County", "");
                    if ("".equals(provinceId) || "".equals(cityId) || "".equals(countyId) || "".equals(province) || "".equals(city) || "".equals(county)) {
                        ToastUtil.showToast("地址不能为空");
                        selfDialog.dismiss();
                        return;
                    }


                    if (dataBean != null) {
                        mPresenter.update(dataBean.getId(),name,contact,tel,lat+"",log+"",provinceId,cityId,countyId,location_info,province,city,county,position,position_name,url,type+"",remarks);
                    }else {
                        mPresenter.insert(name,contact,tel,lat+"",log+"",provinceId,cityId,countyId,location_info,province,city,county,position,position_name,url,type+"",remarks);
                    }

                }

            }else {
                return;
            }
        });
    }

    private void Dialog(String a) {
        selfDialog = new AwaitDialog(this);
        selfDialog.setTitle("提示");
        selfDialog.setMessage(a);
        selfDialog.show();
    }

    @Override
    protected AddMenDianPresenter createPresenter() {
        return new AddMenDianPresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_add_men;
    }


    /**
     * PopupWindow展示
     */
    private void selectImgs() {

        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(AddMenDianActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        menuWindow = new SelectPicPopupWindow(AddMenDianActivity.this) {

            @Override
            public View initView() {
                LayoutInflater inflater = (LayoutInflater) AddMenDianActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View menuview = inflater.inflate(R.layout.item_add_popupwindows, null);

                //新建
                Button friend_item_popupwindows_new = (Button) menuview.findViewById(R.id.friend_item_popupwindows_new);
                //添加
                Button friend_item_popupwindows_add = (Button) menuview.findViewById(R.id.friend_item_popupwindows_add);
                //刷新
                Button friend_item_popupwindows_cancel = (Button) menuview.findViewById(R.id.friend_item_popupwindows_cancel);

                /**
                 * 取消按钮销毁事件
                 * by黄海杰@2015-1-7
                 */
                friend_item_popupwindows_cancel.setOnClickListener(v ->  dismiss());
                friend_item_popupwindows_new.setOnClickListener(v ->{
                    camera();
                });
                friend_item_popupwindows_add.setOnClickListener(v -> gallery());
                return menuview;
            }
        };
        //设置弹窗位置
        menuWindow.showAtLocation(AddMenDianActivity.this.findViewById(R.id.add), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 从相机获取
     */
    public void camera() {
        // 激活相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            tempFile = new File(Environment.getExternalStorageDirectory(),
                    PHOTO_FILE_NAME);
            // 从文件中创建uri
            Uri uri = Uri.fromFile(tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
    }

    /**
     * 从相册获取
     */
    public void gallery() {
        // 激活系统图库，选择一张图片
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }


    /**
     * 判断sdcard是否被挂载
     * @return true表示挂载
     */
    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PHOTO_REQUEST_GALLERY:
                // 从相册返回的数据
                if (data != null) {
                    try {
                        // 得到图片的全路径
                        Uri uri = data.getData();
                        String[] proj = { MediaStore.Images.Media.DATA };
                        Cursor actualimagecursor = AddMenDianActivity.this.managedQuery(uri,proj,null,null,null);
                        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        actualimagecursor.moveToFirst();
                        String img_path = actualimagecursor.getString(actual_image_column_index);
                        File file = new File(img_path);
                        path = uri.getPath();
                        Log.e("AddMenDianPresenter",path);
                        Glide.with(AddMenDianActivity.this).load(uri).into(image);
                        BitmapUtils.saveImage(file);
                        mPresenter.uploadImage(file);
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case PHOTO_REQUEST_CAREMA:

                // 从相机返回的数据
                if (hasSdcard()) {
                    try {

                        Log.e("AddMenDianPresenter",tempFile.getName()+"!!"+tempFile.toString());
                        Glide.with(AddMenDianActivity.this).load(tempFile).into(image);
                        BitmapUtils.saveImage(tempFile);
                        mPresenter.uploadImage(tempFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    ToastUtil.showToast("未找到存储卡，无法存储照片！");
                }
                break;
            case LAT_LOG:
                //地图界面返回的经纬度
                if (data != null) {
                    lat = data.getDoubleExtra("lat", 0.0)+"";
                    log = data.getDoubleExtra("log", 0.0)+"";
                    add_location.setText(lat +","+ log);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public AddMenDianActivity getAddMenDianActivity() {
        return AddMenDianActivity.this;
    }

    @Override
    public TextView getSite() {
        return add_site;
    }

    @Override
    public AwaitDialog getDialog() {
        return selfDialog;
    }

    //上传图片url
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UrlEvent event){
        Log.e("AddMenDianPresenter",event.getUrl());
        url = event.getUrl();
        ToastUtil.showToast("图片上传成功");
    }

    //场所ID
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventSite(SitePosition event){
        position = event.getPosition();
        position_name = event.getName();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.unLoadData();
        EventBus.getDefault().unregister(this);
    }
}
